package com.rk.kbk.controller;
import com.rk.kbk.common.JsonResp;
import com.rk.kbk.dao.MessageDao;
import com.rk.kbk.dao.MessageUnitDao;
import com.rk.kbk.dao.UserDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.Message;
import com.rk.kbk.model.MessageUnit;
import com.rk.kbk.model.User;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by bilibili on 2017/3/14.
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/messageUnit")
public class MessageUnitController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private UserDao userDao;

    @Autowired
    private MessageUnitDao messageUnitDao;

    @Autowired
    private MessageDao messageDao;

    /**
     * 消息中心获取消息列表（骑手、商家、用户）
     *
     */
    @RequestMapping(value = "/getMessageList",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getMessageList(Long userId) {
        User user = userDao.findOne(userId);
        List<MessageUnit> messageUnitList = messageUnitDao.findByUser(user);
        List<Map> messageList = new ArrayList<>();
        for (int i = 0, y = messageUnitList.size(); i < y; i++) {
            Map map = new HashMap();
            MessageUnit messageUnit = messageUnitList.get(i);
            Message message = messageUnit.getMessage();
            map.put("MessageId", message.getId());
            map.put("Title", message.getTitle());
            map.put("gmtDatetime", message.getGmtDatetime());
            map.put("content", message.getContent());
            map.put("is_read", messageUnit.getIsRead());
            map.put("messageUnitId", messageUnit.getId());
            messageList.add(map);

        }
        return JsonResp.ok(messageList);
    }



    /**
     * 消息中心查看消息详情 骑手、商家、用户）
     *
     */
    @RequestMapping(value = "/findOneMessageDetail",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findOneMessageDetail(Long messageUnitId) {
        MessageUnit messageUnit = messageUnitDao.findOne(messageUnitId);
        if (messageUnit.getIsRead() == 0) {
            messageUnit.setIsRead(1);//已读
            messageUnitDao.save(messageUnit);
        }

        Message message = messageUnit.getMessage();
        Map map = new HashMap();
        map.put("MessageId", message.getId());
        map.put("Title", message.getTitle());
        map.put("content", message.getContent());
        map.put("gmtDatetime", message.getGmtDatetime());
        map.put("isRead", messageUnit.getIsRead());
        map.put("messUrl", message.getMessUrl());
        return JsonResp.ok(map);

    }

    /**
     * @添加消息
     * @param message 消息
     * @param userType 用户类型
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addMessageUnit",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addMessageUnit(@RequestBody Message message,Integer userType) {
        log.debug("添加消息");
        //添加消息
        messageDao.save(message);
        List<MessageUnit> messageUnitList = messageUnitDao.findByMessage(message);
        if (messageUnitList.size()!=0){
            messageUnitDao.delete(messageUnitList);
        }
        //添加消息unit
        List<User> users;
        if (userType==0){
             users = userDao.findByUserStatus(1);
        }else{
             users = userDao.findByUserTypeAndUserStatus(userType,1);
        }
        //站内消息
        if(message.getType()==1){
            for(User u:users){
                MessageUnit m = new MessageUnit();
                m.setIsRead(0);
                m.setUser(u);
                m.setMessage(message);
                messageUnitDao.save(m);
            }
        }
        return JsonResp.ok();
    }


    /**
     * @分页查询用户推送消息(jpa方式)
     * @param userId 用户Id
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/pageByUser",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageMessageJpaByUser(Integer pageNum, Integer pageSize,Long userId) {
        log.debug("分页查询消息(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == userId) {
            page = messageUnitDao.findAll(pageable); //无条件分页
        }else{
            page = messageUnitDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        User user = userDao.findOne(userId);
                        expressions.add(cb.equal(root.get("user"),user));
                        return predicate;
                    }, pageable);
        }
//        List<Message> content = page.getContent();
//        for (Message message1 : content) {
//        }
        return JsonResp.ok(new PageDto(page));
    }
}
